/*
 * Copyright 2007 Steven Blundy.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.caree.rpc


import scala.xml.{Elem, Null}

import java.net.URL

/**
 * Provides a connection to a RPC style service
 */
class RpcService(private val conn: SoapConnection) {
  self: Bindings =>
  private val logger = org.apache.log4j.Logger.getLogger(classOf[RpcService])
  /*
  def this(serviceUrl: URL) = { 
    this(SoapConnection.createConnectionForUrl(serviceUrl) match { 
        case Some(conn) => conn 
        case None => throw new SoapException("Url not supported") 
      }) 
  }
  */
    
  /**
   * Sends the rpc call to a remote SOAP service
   */
  def make[T](call: RpcCall[T]): T = {
    val b = binding[T](call.prefix, call.methodName) match {
      case Some(bg) => bg
      case None => throw new SoapException("Binding not found for " + call.prefix + ":" + call.methodName)
    }
    
    val msg = Elem(call.prefix, call.methodName, Null, b.namespace)
    
    return conn.send(msg) match { 
      case StandardResponse(_, body) if body.length == 1 => b.response.fromXml(body.last)
      case _ => null.asInstanceOf[T]
    }
  }
}

/**
 * The identification and parameters of the message to be send. Subtyping with the identification 
 * data hardcoded is encouraged.
 */
case class RpcCall[T](prefix: String, methodName: String, params: Any*)
